//
//  WSUser.m
//  CharonTVProject
//
//  Created by karong on 2023/6/16.
//

#import "WSUser.h"
#import <Firebase.h>
#import <FirebaseAuth/FirebaseAuth.h>
#import "SuperLuckyKeyChainStore.h"
#import "WSUserRequest.h"

@implementation WSUser

@end

@implementation WSUserCenter

static WSUserCenter *instance = nil;

+ (NSArray *)mj_ignoredPropertyNames {
    return @[@"login", @"qtoken"];
}

+ (instancetype)defaultSession {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init {
    if([appUserDefaults objectForKey:@"WSUserCenter"]) {
        self = [[WSUserCenter alloc] mj_setKeyValues:[appUserDefaults objectForKey:@"WSUserCenter"]];
    }
    else {
        self = [super init];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:UIApplicationWillTerminateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:UIApplicationDidEnterBackgroundNotification object:nil];
    return self;
}

- (BOOL)isLogin {
    if (self.token) {
        return YES;
    }
    return NO;
}

- (void)logOut {
    [appUserDefaults removeObjectForKey:@"WSUserCenter"];
    [appUserDefaults synchronize];
    instance = [[WSUserCenter alloc] init];
    // 登录成功instance被重新赋值，會导致没有注册通知。
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [self save];
    // 退出第三方登录
    [[FIRAuth auth] signOut:nil];
}

- (void)save {
    [appUserDefaults setObject:instance.mj_keyValues forKey:@"WSUserCenter"];
    [appUserDefaults synchronize];
}

- (void)logIn:(WSUserCenter *)userCenter {
    instance = userCenter;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [self save];
}

+ (NSString *)uuid {
    NSString * str = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString * strUUID = (NSString * )[SuperLuckyKeyChainStore load:str];
    if (WSIsNullOrEmpty(strUUID)){
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        strUUID = (NSString * )CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,uuidRef));
        //将该uuid保存到kevchain-
        [SuperLuckyKeyChainStore save:str data:strUUID];
    }
    return strUUID;
}

- (void)getUserInfocharonTV_Request {
    [WSUserRequest getcharonTV_UserInfoWithUser_id:appUserCenter.id success:^(id obj) {
        NSString * token = self.token;
        if (WSIsNullOrEmpty(token)) {
            [appUserCenter logOut];
            [WSToast simple:@"長期未登錄，請重新登錄"];
        }
        else {
            [self logIn:obj];
            self.token = token;
            [[NSNotificationCenter defaultCenter]postNotificationName:WSRefreshUserInfoNotification object:nil];
        }
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}
@end
